package com.cwj.film.AOP;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cwj.common.domain.DownloadRecord;
import com.cwj.common.domain.film;
import com.cwj.common.domain.user;
import com.cwj.common.utils.utils;
import com.cwj.common.vo.film.aboutSo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.BeanUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Aspect
@Component
@Order(0)
public class downFilmAop {
    @Resource
    private com.cwj.film.dao.downRecDao downRecDao;
    @Resource
    private com.cwj.film.dao.filmDao filmDao;
    @Resource
    private com.cwj.film.dao.userDao userDao;
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private HttpServletRequest request;
    @Pointcut("execution(* com.cwj.film.service.inter.about.downAll(..))")
    private void downFilmAllPointcut(){}
    @Pointcut("execution(* com.cwj.film.service.inter.about.downFilm(..))")
    private void downFilmByVideoPointcut()  {}
    @After("downFilmByVideoPointcut()")
    public void logDownFilmByVideo() throws JsonProcessingException {
        DownloadRecord record = GetDownloadRecord();
        aboutSo aboutSo =(aboutSo) request.getAttribute("aboutSo");
        record.setFilmEpisode(aboutSo.getVideo());
        downRecDao.insert(record);
    }
    @After("downFilmAllPointcut()")
    public void logDownFilmAll() throws JsonProcessingException {
        DownloadRecord record = GetDownloadRecord();
        record.setFilmEpisode("all");
        downRecDao.insert(record);
    }
    private DownloadRecord GetDownloadRecord() throws JsonProcessingException {
        DownloadRecord record = new DownloadRecord();
        Object aboutSo = request.getAttribute("aboutSo");
        film film = new film();
        BeanUtils.copyProperties(aboutSo,film);


        Integer fid = (Integer) filmDao.selectObjs(new QueryWrapper<film>().allEq(objectMapper.readValue(objectMapper.writeValueAsString(film),new TypeReference<Map<String,String>>(){})).select("fid")).get(0);
        record.setFid(fid);
        Map<String, String> userByCookie = utils.GetUserByCookie(request.getCookies());
        List<Object> uidList = userDao.selectObjs(new QueryWrapper<user>().allEq(userByCookie).select("uid"));

        Integer    uid = uidList!=null&&uidList.size()>0 ? (Integer) uidList.get(0) : 0;
        record.setUid(uid);
        return  record;
    }
}
